/**
 * view
 *
 * @param {Object} $
 * @param {Object} window
 * @param {Object} document
 */

(function(R, _, $, window, document) {

  R.$ = $;

  // List of view options to be set as properties.
  var viewOptions = ['el', 'id', 'attributes', 'className', 'tagName', 'events'];

  var View = R.View = function(options) {
    this.cid = _.uniqueId('view');
    _.extend(this, _.pick(options, viewOptions));
    this._ensureElement();
    //must do synchronous action for the order
    this.initialize.apply(this, arguments);
  };

  _.extend(View.prototype, {
    // The default `tagName` of a View's element is `"div"`.
    tagName: 'div',

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // **render** is the core function that your view should override, in order
    // to populate its element (`this.el`), with the appropriate HTML. The
    // convention is for **render** to always return `this`.
    render: function() {
      return this;
    },

    //just remove out of DOM
    removeElement: function() {
      this.el.parentNode.removeChild(this.el);
    },

    // Change the view's element (`this.el` property) and re-delegate the
    // view's events on the new element.
    setElement: function(element) {
      // this.undelegateEvents();
      this._setElement(element);
      // this.delegateEvents();
      return this;
    },
    _createElement: function (tagName) {
      return document.createElement(tagName);
    },

    _setElement: function(el) {
      this.$el = el[0] ? el : R.$(el);
      this.el = this.$el[0];
    },

    _setAttributes: function(attributes) {
      this.$el.attr(attributes);
    },
    // Ensure that the View has a DOM element to render into.
    // If `this.el` is a string, pass it through `$()`, take the first
    // matching element, and re-assign it to `el`. Otherwise, create
    // an element from the `id`, `className` and `tagName` properties.
    _ensureElement: function() {
      if (!this.el) {
        var attrs = _.extend({}, _.result(this, 'attributes'));
        if (this.id) attrs.id = _.result(this, 'id');
        if (this.className) attrs['class'] = _.result(this, 'className');
        this.setElement(this._createElement(_.result(this, 'tagName')));
        this._setAttributes(attrs);
      } else {
        this.setElement(_.result(this, 'el'));
      }
    },



  });

  // Set up inheritance for the view .
  View.extend = R.sextend;

})(rweb, _, $, window, document);
